package com.yonyou.gmcc.gateway.wechat.interceptor;

import io.jsonwebtoken.Claims;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.yonyou.gmcc.gateway.wechat.service.interfaces.WechatApiServiceInterface;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WechatAuthCheckInterceptor implements HandlerInterceptor{

	private static Logger logger=Logger.getLogger(WechatAuthCheckInterceptor.class);
	public static final String SESSION_USER_STR = "sessionUser";
	private static String auth2url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
	@Autowired
	private WechatApiServiceInterface wechatApiService;

	@Override
	public boolean preHandle(HttpServletRequest req,
			HttpServletResponse res, Object handler) throws Exception {

//		logger.info("---------------WechatAuthCheckInterceptor begin,");
		//Object user =  req.getSession().getAttribute(SESSION_USER_STR);
		
        String cookieToken=getCookie(req,res);
		String code = req.getParameter("code");
/*		if(code==null||"".equals(code)){
			String tmp=req.getRequestURL().toString();
			String uri=auth2url.replace("REDIRECT_URI", URLEncoder.encode(tmp, "UTF-8")).replace("SCOPE", "snsapi_base");
			res.sendRedirect(uri);
		}*/
		//String openid=wechatApiService.getOpenidByCode(code);
		//logger.info("---------openid="+openid);
		//token="";
//		if ("".equals(cookieToken)) {
//			if (code!=null) {
//	            writeCookie(req,res,code);
//				
//			} else {
//				return true;
//			}
//		}else{
//			Claims claims=JwtHelper.parseJWT(cookieToken);
//			if(claims==null){//如果jwtToken过期，重新生成一个
//	            writeCookie(req,res,code);
//			}else{
//				String md5openid=(String)claims.get("md5openid");
//				logger.info("--------cookie-jwt-md5openid="+md5openid);
//				logger.info("--------cookie-jwttoken="+cookieToken);
//			}
//		}
		return true;
	}
	private String getJwtToken(HttpServletRequest req,String code){

		String openid=wechatApiService.getOpenidByCode(code);
		logger.info("---------openid="+openid);
		//拼装jwtAccessToken  
/*		String md5openid=Md5Utils.getMD5(openid);
		logger.info("---------md5openid="+md5openid);
        String jwtToken = JwtHelper.createJWT(md5openid, "",  
                "role", "clientid", "",  
                60*30 );  //30分钟
*/        return "";
	}
	private String getCookie(HttpServletRequest req, HttpServletResponse response){
		Cookie[] cookies = req.getCookies();//这样便可以获取一个cookie数组
		if(cookies==null)
			return "";
		for(Cookie cookie : cookies){
		    if("wechat.open.api".equals(cookie.getName()))
		      return cookie.getValue(); // get the cookie value
		}
		return "";
	}
	private void writeCookie(HttpServletRequest req, HttpServletResponse response,
			String code){
		String jwtToken=getJwtToken(req,code);
		response.setCharacterEncoding("GBK");
		response.setContentType("text/html;charset=GBK");
		Cookie cookie; 
		cookie=new Cookie("wechat.open.api",jwtToken);//用户ID 
		cookie.setMaxAge(60*60);//cookie时间 
		cookie.setPath(req.getContextPath()); //根据个人的不用，在不同功能的路径下创建 
		response.addCookie(cookie); 
        logger.info("---------jwtToken="+jwtToken);
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest req,
			HttpServletResponse res, Object handler, Exception ex)
			throws Exception {
	}
}
